﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;


namespace SmartBlast
{
    public partial class frmEmployees : Form
    {
        private static string TABLE_NAME = "Employees";
        private static string[] HEADERS = new string[] { "Id", "Name", "Username", "Password", "Job", "Address", "Email", "Birth Date", "Permission" };
        private static string[] FIELD_NAMES = new string[] { "Id", "Name", "Username", "Password", "Job", "Address", "Email", "Birth_Date", "Permission" };
        
        private string[] fields;
        private DataTable employeesDataTable;
        private bool editable = false;
        private DataBase_BUS databaseBUS;
        private Main main;

        public frmEmployees(Main main)
        {
            this.main = main;
            InitializeComponent();
            databaseBUS = DataBase_BUS.getInstance();
           
        }

        private void btn_search_Click(object sender, EventArgs e)
        {
            if(txtEmail.Text != "" && !isValidEmailAddress(txtEmail.Text)) {
                MessageBox.Show("\nPlease input valid email address", "Invalid Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            collectFields();
            employeesDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, FIELD_NAMES, fields);
            refresh();
        }

        private void btn_add_Click(object sender, EventArgs e)
        {
            if (!noFieldsAreBlank()) {
                MessageBox.Show("\nPlease input all fields", "Missing Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

             if(!isValidEmailAddress(txtEmail.Text)) {
                MessageBox.Show("\nPlease input valid email address", "Invalid Information", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            else
            {
                collectFields();
                try
                {
                   databaseBUS.insertRecordIntoTable(TABLE_NAME, fields);
                    clearTextBoxes();
                    showAll();
                }
                catch
                {
                    gridEmployees.Visible = false;
                    lbl_NoResults.Visible = true;
                    lbl_NoResults.Text = "There is an employee with the same Serial Number. \n Please select another code";
                }

            }
        }

        private void btn_Clear_Click(object sender, EventArgs e)
        {
            clearTextBoxes();
        }

        private void btn_showAll_Click(object sender, EventArgs e)
        {
            showAll();
        }

        private void collectFields()
        {
            fields = new string[] { txtId.Text, "'" + txtName.Text + "'","'" + txtUserName.Text + "'","'"+txtPassword.Text+"'",
                "'"+txtJob.Text+"'","'"+txtAddress.Text+"'","'"+txtEmail.Text+"'",
                (dateBirthDate.Checked==true)? "'"+dateBirthDate.Value.ToString()+"'" : "", cmbPermission.Text };
            
        }

        private Boolean noFieldsAreBlank()
        {
            return (txtId.Text != "" && txtName.Text != "" && txtUserName.Text != "" && txtPassword.Text != "" 
                && txtJob.Text != "" && txtAddress.Text != "" && txtEmail.Text != "" 
                && dateBirthDate.Checked == true && cmbPermission.SelectedIndex != -1);
        }

        private void clearTextBoxes()
        {
            txtId.Text = txtName.Text = txtUserName.Text = txtPassword.Text = txtJob.Text =
                txtAddress.Text = txtEmail.Text = "";
            dateBirthDate.Checked = false;
            cmbPermission.SelectedIndex = -1;
        }

        private void showAll()
        {
            employeesDataTable = databaseBUS.selectRecrordFromTable(TABLE_NAME, null, null);
            refresh();
        }


        private void refresh()
        {
            if (employeesDataTable.Rows.Count == 0)
            {
                gridEmployees.Visible = false;
                lbl_NoResults.Visible = true;
            }
            else
            {
                lbl_NoResults.Visible = false;
                gridEmployees.Visible = true;
                gridEmployees.DataSource = employeesDataTable;
                gridEmployees.Columns[3].ReadOnly = true;
            }
        }

        private void gridEmployees_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string id = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[3].Value.ToString();
            int index = (((System.Windows.Forms.DataGridView)(sender)).CurrentCell).ColumnIndex;

            if (index == 0) //click on "edit"
            {
                ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.DefaultCellStyle.ForeColor = Color.Red;
                editable = true;
            }

            else if (index == 1 && editable) //click on "save"
            {
                string name = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[4].Value.ToString();
                string username = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[5].Value.ToString();
                string password = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[6].Value.ToString();
                string job = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[7].Value.ToString();
                string address = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[8].Value.ToString();
                string email = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[9].Value.ToString();
                string birthdate = ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[10].Value.ToString();
                string permission= ((System.Windows.Forms.DataGridView)(sender)).CurrentRow.Cells[11].Value.ToString();


                fields = new string[] { id, "'" + name + "'", "'" + username + "'", "'" + password + "'",
                    "'" + job+ "'","'" + address+ "'","'" + email+ "'","'" + birthdate+ "'",permission};

                databaseBUS.updateRecordInTable(TABLE_NAME, FIELD_NAMES, fields, FIELD_NAMES[0], fields[0]);

                MessageBox.Show("The employee was successfully updated");
                showAll();
                editable = false;
            }

            else if (index == 2) //click on "delete"
            {
                DialogResult dialogResult = MessageBox.Show("Are you sure you want to delete the employee?", "Delete", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    databaseBUS.deleteRecordFromTable(TABLE_NAME, FIELD_NAMES[0], id);
                    MessageBox.Show("The employee was successfully deleted");
                }
                                
                showAll();
            }
        }

        private void txtId_TextChanged(object sender, EventArgs e)
        {
            int id;
            bool success = int.TryParse(txtId.Text, out id);
            String prevText = txtId.Text.Substring(0, Math.Max(0, txtId.Text.Length - 1));
            if (!success)
            {
                txtId.Text = prevText;
            }
            else
            {
                txtId.Text = id.ToString();
            }
        }


        private void btn_exit_Click(object sender, EventArgs e)
        {
            
            this.Hide();
        }


        private void frmEmployees_Load(object sender, EventArgs e)
        {
            this.CenterToScreen();
            cmbPermission.SelectedIndex = -1;
        }

        public bool isValidEmailAddress(string emailAddress)
        {
            // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
            if (emailAddress.IndexOf("@") > 0)
            {
                if (emailAddress.IndexOf(".", emailAddress.IndexOf("@")) > emailAddress.IndexOf("@"))
                {
                    return true;
                }
            }
            return false;
        }







    }
}
